/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package fanta.framework.manager;

import javax.persistence.EntityManager;
import org.apache.log4j.Logger;
import fanta.framework.manager.EMFactoryManager;

/**
 *
 * @author alessandro de troia
 */
public class ConnectionManager {
    private static final Logger logger = Logger.getLogger(ConnectionManager.class);
    EntityManager entityManager = null;


    public void createEntityManager() {
        try {
            entityManager = EMFactoryManager.getEntityManagerFactory().createEntityManager();
        } catch (Exception e) {
            logger.error("errore in getEntityManagerFactory", e.fillInStackTrace());
        }
    }

    public EntityManager getEntityManager() {
        if (entityManager == null) {
            createEntityManager();
        } else {

            try {
                //logger.debug("test if entityManager is open");
                if (!entityManager.isOpen()) {
//                    logger.debug("entityManager is open");
                    //logger.debug("tring to close entityManager");
                    entityManager.close();
//                    logger.debug("entityManager closed");
                    createEntityManager();
                }
            } catch (Exception e) {
                logger.error("exception in getEntityManager create a new EntityManager");
                createEntityManager();
            }
        }
        try {
            entityManager.createNativeQuery("select 1").getSingleResult();
        } catch (Exception e) {
            logger.error("Exception: "+e.getMessage(), e.fillInStackTrace());
            createEntityManager();
        }
        return entityManager;
    }

    public void closeConnection() {
        try {
            if (entityManager != null) {
                entityManager.close();
            }
        } catch (Exception e) {
            logger.fatal("Impossible to CLOSE EntityManger ", e);
        }
    }
}
